define(['jquery', 'bootstrap', 'backend', 'table', 'form', 'selectpage'], function ($, undefined, Backend, Table, Form, selectPage) {

    var Controller = {
        index: function () {
            var aid = $('#assign-data-ids').val()
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'adproject/index' + location.search,
                    add_url: 'adproject/add' + (aid ? '?aid=' + aid : ''),
                    edit_url: 'adproject/edit',
                    del_url: 'adproject/del',
                    table: 'ad_project',
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'weigh',
                queryParams: function (params) {
                    params.zone_id = aid
                    return params
                },
                columns: [
                    [
                        {checkbox: true},
                        {field: 'title', title: __('标题'), operate: 'LIKE'},
                        {
                            field: 'image',
                            title: __('图片'),
                            operate: false,
                            events: Table.api.events.image,
                            formatter: function (value, row, index) {
                                if (value) {
                                    return Table.api.formatter.image.call(this, value, row, index)
                                }
                            }
                        },
                        {
                            field: 'betype',
                            title: __('落地'),
                            searchList: {user: '用户页面', url: '链接'},
                            formatter: Table.api.formatter.label,
                            custom: {user: 'warning', url: 'info'}
                        },
                        {
                            field: 'user.username',
                            title: __('用户'),
                            formatter: Table.api.formatter.label
                        },

                        {
                            field: 'user_page_type',
                            title: __('页面类型'),
                            searchList: {demand: '需求详情', goods: '服务详情', shop: '店铺主页', home: '个人主页'},
                            formatter: function (value, row, index) {
                                if (row.betype === 'user') {
                                    return Table.api.formatter.normal.call(this, value, row, index)
                                }
                            },
                            custom: {demand: 'success', goods: 'info', shop: 'warning', home: 'navy'}
                        },
                        {
                            field: 'effectime',
                            title: __('生效时间'),
                            formatter: Table.api.formatter.datetime,
                            operate: 'RANGE',
                            addclass: 'datetimerange',
                            sortable: true
                        },
                        {
                            field: 'expiretime',
                            title: __('过期时间'),
                            formatter: function (value, row, index) {
                                if (row.expire === 'time') {
                                    return Table.api.formatter.datetime.call(this, value, row, index)
                                } else {
                                    return '长期'
                                }
                            },
                            operate: 'RANGE',
                            addclass: 'datetimerange',
                            sortable: true
                        },
                        {
                            field: 'weigh',
                            title: __('权重'),
                            sortable: true,
                            visible: false
                        },
                        {
                            field: 'create_time',
                            title: __('创建时间'),
                            formatter: Table.api.formatter.datetime,
                            operate: 'RANGE',
                            addclass: 'datetimerange',
                            sortable: true,
                            visible: false
                        },
                        {
                            field: 'update_time',
                            title: __('更新时间'),
                            formatter: Table.api.formatter.datetime,
                            operate: 'RANGE',
                            addclass: 'datetimerange',
                            sortable: true,
                            visible: false
                        },
                        {
                            field: 'operate',
                            title: __('Operate'),
                            table: table,
                            events: Table.api.events.operate,
                            formatter: Table.api.formatter.operate
                        }
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        add: function () {
            Controller.api.bindevent();
        },
        edit: function () {
            Controller.api.bindevent();
        },
        api: {
            bindevent: function () {
                var expireUpdate = function () {
                    let expiretype = $('input[name="row[expire]"]:checked').val()
                    let expireTimeNode = $('input[name="row[expiretime]"]');
                    if (expiretype === 'time') {
                        let date = new Date;
                        date.setMonth(date.getMonth() + 1)
                        expireTimeNode.val(Moment(date.getTime()).format('YYYY-MM-DD HH:mm:ss'))
                        $('.expire-time-field').show()
                    } else {
                        $('.expire-time-field').hide()
                        expireTimeNode.val('2106-02-07 14:28:15')
                    }
                }
                var update = function () {
                    let betype = $('input[name="row[betype]"]:checked').val()
                    let user_id = $('input[name="row[user_id]"]').val()
                    let userPageType = $('input[name="row[user_page_type]"]:checked').val()
                    $('[class*="-type-group"]').hide()
                    $('[class*="-betype-group"]').hide()
                    $('.' + betype + '-type-group').show()
                    if (user_id) {
                        $('.select-betype').show()
                        $('.' + userPageType + '-betype-group').show()
                    } else {
                        $('.select-betype').hide()
                    }

                    $(".select-be").selectPage({
                        eAjaxSuccess: function (data) {
                            data.list = typeof data.rows !== 'undefined' ? data.rows : (typeof data.list !== 'undefined' ? data.list : []);
                            data.totalRow = typeof data.total !== 'undefined' ? data.total : (typeof data.totalRow !== 'undefined' ? data.totalRow : data.list.length);
                            return data;
                        },
                        params: function () {
                            return {custom: {user_id: $('input[name="row[user_id]"]').val()}};
                        }
                    })
                    expireUpdate()
                }

                update()
                $(document).on('change', 'input[name="row[betype]"]', function () {
                    update()
                }).on('change', '#search_user', function () {
                    $('.select-be').val('')
                    $.ajax({
                        url: 'user/user/search',
                        data: {word: this.value},
                        success: function (user) {
                            if (!user) {
                                user = {}
                                Toastr.error('没有这个用户');
                            }
                            $('input[name="row[user_id]"]').val(user.id || '')
                            update()
                        }
                    })
                }).on('change', 'input[name="row[user_page_type]"]', function () {
                    update()
                }).on('change', 'input[name="row[expire]"]', function () {
                    expireUpdate()
                })

                $.validator.config({
                    rules: {
                        isUrl: function () {
                            return $('input[name="row[betype]"]:checked').val() === 'url'
                        },
                        isUser: function () {
                            return $('input[name="row[betype]"]:checked').val() === 'user'
                        },
                        isDemand: function () {
                            return this.validator.rules.isUser() && $('input[name="row[user_page_type]"]:checked').val() === 'demand'
                        },
                        isGoods: function () {
                            return this.validator.rules.isUser() && $('input[name="row[user_page_type]"]:checked').val() === 'goods'
                        },
                        isExpireTime: function () {
                            return $('input[name="row[expire]"]:checked').val() === 'time'
                        }
                    }
                });
                Form.api.bindevent($("form[role=form]"));
            }
        }
    };
    return Controller;
});